﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Web;
using Utity;

namespace PCTInterface.Common
{
    public class Tools
    {
        public static Dictionary<string, object> ConvertParams()
        {
            HttpContext context = HttpContext.Current;
            HttpRequest req = context.Request;
            if (!req.ContentType.ToLower().Contains("json"))
            {
                throw new NullReferenceException("ContentType异常");
            }
            byte[] byts = new byte[req.InputStream.Length];
            req.InputStream.Read(byts, 0, byts.Length);
            string cipherText = System.Text.Encoding.UTF8.GetString(byts);
            string json= Utity.AESSupport.AESDecryptIV(cipherText);

            if (!CheckToken(json))
            {
                throw new NullReferenceException("Token错误");
            }
            Dictionary<string, object> dic = Utility.JSONHelper.Instance.JavaScriptDeserializationMachion<Dictionary<string, object>>(json);
            //if (!dic.ContainsKey("EHUSER"))
            //{
            //    dic["EHUSER"] = context.Session[Constant.CONST_SESSION_USER];
            //}

            if (!dic.ContainsKey("DB_NAME"))
            {
                dic["DB_NAME"] = System.Configuration.ConfigurationManager.AppSettings["DEFAULT_DB_NAME"];
            }
            return dic;
        }

        //参数转换
        private static string ToUrlString(IDictionary<string, object> formParams)
        {
            string strQuery = "?";
            foreach (string key in formParams.Keys)
            {
                strQuery += key + "=" + formParams[key].ToString() + "&";
            }

            return strQuery.Substring(0, strQuery.Length - 1);
        }


        //验证权限信息
        public static bool CheckToken(string json)
        {
            HttpRequest request = HttpContext.Current.Request;
            string request_token = request.Headers["REQUEST_TOKEN"];           
            Utity.AppHelper app = new Utity.AppHelper();
            string compare_token = app.ConvertToMD5(json+ Utity.RSASupport.GetAppKeyt());
            return request_token.Equals(compare_token);
        }

        public static string GenerateSign(string json)
        {
            Utity.AppHelper app = new Utity.AppHelper();
            return app.ConvertToMD5(json + Utity.RSASupport.GetAppKeyt());
        }

        private static List<string> parseIdentifierOptions()
        {
            if (string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings["Identifier"]))
            {
                return null;
            }
            return new List<string>(ConfigurationManager.AppSettings["Identifier"].Split('|'));
        }

        public static List<string> parseOptions(string typeString, char[] splitString)
        {
            if (string.IsNullOrWhiteSpace(ConfigurationManager.AppSettings[typeString]))
            {
                return null;
            }
            return new List<string>(ConfigurationManager.AppSettings[typeString].Split(splitString));
        }

        public static void DownLoad(string filePath, string type)
        {
            HttpContext context = HttpContext.Current;
            try
            {
                if (string.IsNullOrEmpty(filePath))
                {
                    context.Response.End();
                }
                string filename = context.Server.UrlDecode(filePath);

                context.Response.Clear();
                context.Response.Charset = "utf-8";//设置输出的编码
                context.Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息，为"文件下载/另存为"对话框指定默认文件名
                context.Response.AddHeader("Content-Disposition", "inline; filename=" + context.Server.UrlEncode(Path.GetFileName(filename)));

                // 指定返回的是一个不能被客户端读取的流，必须被下载
                switch (type.ToLower())
                {
                    case "pdf":
                        context.Response.ContentType = "application/pdf";
                        break;
                    case "gif":
                        context.Response.ContentType = "image/gif";
                        break;
                    case "jpg":
                        context.Response.ContentType = "image/jpeg";
                        break;
                    case "zip":
                        context.Response.ContentType = "application/zip";
                        break;
                    case "excel":
                        context.Response.ContentType = "application/x-excel";
                        break;
                    case "tif":
                        context.Response.ContentType = "application/x-tif";
                        break;
                    case "word":
                        context.Response.ContentType = "application/msword";
                        break;
                }

                string target = System.Configuration.ConfigurationManager.AppSettings["DownloadTarget"];
                if (string.IsNullOrEmpty(target))
                {
                    System.IO.FileInfo file = new System.IO.FileInfo(filename);
                    context.Response.AddHeader("Content-Length", file.Length.ToString());
                    // 把文件流发送到客户端
                    context.Response.WriteFile(filename);
                }
                else
                {
                    WebClient wClient = new WebClient();
                    string __url = target + "?path=" + filename;
                    Byte[] bytes = wClient.DownloadData(__url);
                    // 添加头信息，指定文件大小，让浏览器能够显示下载进度
                    context.Response.AddHeader("Content-Length", bytes.Length.ToString());
                    context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                }

                context.Response.Flush();
            }
            catch (Exception)
            {
                context.Response.Write("文件不载出错，请稍后下载");
                context.Response.Flush();
            }
        }

        public static string GetContentType(string type)
        {
            string contentType = string.Empty;
            switch (type.ToLower())
            {
                case "pdf":
                    contentType = "application/pdf";
                    break;
                case "img":
                    contentType = "image/Gif";
                    break;
                case "bmp":
                    contentType = "application/x-bmp";
                    break;
            }

            return contentType;
        }

        public static IDictionary<string, object> GetSPinfo(IDictionary<string, object> formParams)
        {
            if (!formParams.Keys.Contains(Constant.DB_NAME) || string.IsNullOrEmpty(formParams[Constant.DB_NAME].ToString()))
            {
                formParams[Constant.DB_NAME] = Constant.DEFAULT_DB;
            }

            if (!formParams.Keys.Contains(Constant.TB_NAME) || !formParams.Keys.Contains(Constant.OP_NAME))
            {
                formParams["RETURN_CODE"] = "-1";
                formParams["RETURN_MESSAGE"] = "未找到数据库/表/操作名称";
                return formParams;
            }

            string DB_NAME = formParams[Constant.DB_NAME].ToString().ToUpper() != "GLOBAL" ? "MALO_" + formParams[Constant.DB_NAME].ToString().ToUpper() : formParams[Constant.DB_NAME].ToString().ToUpper();
            string TB_NAME = formParams[Constant.TB_NAME].ToString().ToUpper();
            string OP_NAME = formParams[Constant.OP_NAME].ToString().ToUpper();
            string SP_NAME = string.Format("{0}_{1}_{2}", "SP", TB_NAME, OP_NAME);

            //if (!SP_Class.Instance.SP_PARAMS.ContainsKey(SP_NAME))
            //{
            //    formParams["RETURN_CODE"] = "-1";
            //    formParams["RETURN_MESSAGE"] = "未找到存储过程";
            //    return formParams;
            //}

            //if (!SP_Class.Instance.SP_PARAMS.ContainsKey(formParams[Constant.DB_NAME].ToString().ToUpper()))
            //{
            //    formParams["RETURN_CODE"] = "-1";
            //    formParams["RETURN_MESSAGE"] = "未找到数据库";
            //    return formParams;
            //}
            if (!formParams.ContainsKey(Constant.SP_NAME))
            {
                formParams[Constant.SP_NAME] = SP_NAME;//SP_Class.Instance.SP_PARAMS[SP_NAME];
            }
            formParams[Constant.DB_NAME] = DB_NAME;//SP_Class.Instance.SP_PARAMS[formParams[Constant.DB_NAME].ToString().ToUpper()];

            return formParams;
        }

        public static byte[] StreamToBytes(Stream stream)
        {
            List<byte> bytes = new List<byte>();
            int temp = stream.ReadByte();
            while (temp != -1)
            {
                bytes.Add((byte)temp);
                temp = stream.ReadByte();
            }

            return bytes.ToArray();
        }
    }
}